package com.ruoyi.web.controller.estate;

import java.util.List;
import java.util.ArrayList;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.estate.House;
import com.ruoyi.system.service.estate.IHouseService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.system.domain.estate.Resident;
import com.ruoyi.system.service.estate.IResidentService;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 房屋管理Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/estate/house")
public class HouseController extends BaseController
{
    @Autowired
    private IHouseService houseService;

    @Autowired
    private IResidentService residentService;

    /**
     * 查询房屋列表
     */
    @PreAuthorize("@ss.hasPermi('estate:house:list')")
    @GetMapping("/list")
    public TableDataInfo list(House house)
    {
        startPage();
        List<House> list = houseService.selectHouseList(house);
        return getDataTable(list);
    }

    /**
     * 查询房屋列表（匿名访问，用于注册页面）
     */
    @Anonymous
    @GetMapping("/listForRegister")
    public AjaxResult listForRegister()
    {
        House house = new House();
        house.setStatus("0"); // 只查询正常状态的房屋
        List<House> list = houseService.selectHouseList(house);
        return AjaxResult.success(list);
    }

    /**
     * 导出房屋列表
     */
    @PreAuthorize("@ss.hasPermi('estate:house:export')")
    @Log(title = "房屋管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(House house)
    {
        List<House> list = houseService.selectHouseList(house);
        ExcelUtil<House> util = new ExcelUtil<House>(House.class);
        return util.exportExcel(list, "房屋数据");
    }

    /**
     * 获取房屋详细信息
     */
    @PreAuthorize("@ss.hasPermi('estate:house:query')")
    @GetMapping(value = "/{houseId}")
    public AjaxResult getInfo(@PathVariable("houseId") Long houseId)
    {
        return AjaxResult.success(houseService.selectHouseById(houseId));
    }

    /**
     * 新增房屋
     */
    @PreAuthorize("@ss.hasPermi('estate:house:add')")
    @Log(title = "房屋管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody House house)
    {
        return toAjax(houseService.insertHouse(house));
    }

    /**
     * 修改房屋
     */
    @PreAuthorize("@ss.hasPermi('estate:house:edit')")
    @Log(title = "房屋管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody House house)
    {
        return toAjax(houseService.updateHouse(house));
    }

    /**
     * 删除房屋
     */
    @PreAuthorize("@ss.hasPermi('estate:house:remove')")
    @Log(title = "房屋管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{houseIds}")
    public AjaxResult remove(@PathVariable Long[] houseIds)
    {
        return toAjax(houseService.deleteHouseByIds(houseIds));
    }

    /**
     * 获取用户的房屋列表
     */
    @Anonymous
    @GetMapping("/userHouses")
    public AjaxResult getUserHouses()
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询用户关联的住户信息
            Resident resident = new Resident();
            resident.setUserId(userId);
            List<Resident> residents = residentService.selectResidentList(resident);
            
            if (residents.isEmpty())
            {
                return AjaxResult.success(new ArrayList<>());
            }
            
            // 获取住户关联的房屋ID
            List<House> houses = new ArrayList<>();
            for (Resident res : residents)
            {
                House house = houseService.selectHouseById(res.getHouseId());
                if (house != null)
                {
                    houses.add(house);
                }
            }
            
            return AjaxResult.success(houses);
        } catch (Exception e) {
            // 用户未登录或会话过期，返回空列表
            return AjaxResult.success(new ArrayList<>());
        }
    }
} 